global.Acan = require('../lib/Acan')
require('../lib/Adebug')

process.on('unhandledRejection', (reason, p) => {
  console.log(reason, p)
})

// 正式环境的开启错误捕捉，防止进程挂掉
process.on('uncaughtException', function(err) {
  console.log(err)
})

global.tables = {}
global.conf = require(process.env.NODE_ENV === 'dev' ? './conf' : './line')
require('./cron.js') // 计划任务

global._inc = Acan.random(16, 99)
setInterval(() => { _inc = Acan.random(16, 99) }, 1000) // 每秒重置计数器

const getNetworkInfo = () => {
  var os = require('os')
  var nI = os.networkInterfaces()
  var ipLs = []
  var serverIps = []
  var ipList = {}
  var macList = []
  var realIp = ''
  for (var i in nI) {
    if (typeof (nI[i]) !== 'object') continue
    nI[i].forEach((v) => {
      if (Acan.regexp.ipv4.test(v.address)) {
        if (Acan.inArr(v.address, ['127.0.0.1', '0.0.0.0'])) return
        ipLs.push(v.address)
        ipList[v.address] = v.mac
        macList[v.mac] = v.address
      }
      if (!v.internal) serverIps.push(v.address)
    })
  }
  serverIps.forEach((v) => {
    if (/^(10\.|192\.168\.|172\.1[6-9]\.|172\.2[0-9]\.|172\.3[0-1]\.)/.test(v)) {
      if (!realIp) realIp = v
    } else if (/^[\d]{1,3}\.[\d]{1,3}\.[\d]{0,3}\.[\d]{1,3}$/.test(v)) {
      if (!realIp || /(10\.|192\.168\.|172\.1[6-9]\.|172\.2[0-9]\.|172\.3[0-1]\.)/.test(realIp)) {
        realIp = v
      }
    }
  })
  return { serverIps: serverIps, ipMac: ipList, macIp: macList, ips: ipLs, realIp: realIp }
}
Object.assign(conf, getNetworkInfo(0))

const fs = require('fs')
const Fn = require('./fn.js')

Acan.mkdirs(`${conf.db}/snapShot`)
Acan.mkdirs(`${conf.db}/log/${Acan.time('Ymd')}`)

global.caches = {
  add(hash, val) {
    this.data[hash] = val
    if (!this.hash[this.hour]) this.hash[this.hour] = []
    this.hash[this.hour].push(hash)
  },
  data: {},
  hash: {},
  hour: Acan.time('YmdH')
}

setInterval(() => {
  caches.hour = Acan.time('YmdH')
  Acan.mkdirs(`${conf.db}/log/${Acan.time('Ymd')}`)
}, 60000) // 每分钟任务
setInterval(() => {
  const preHour = Acan.time('YmdH', Acan.time() - 3600)
  if (caches.hash[preHour]) {
    caches.hash[preHour].map(hash => {
      delete caches.data[hash]
    })
    delete caches.hash[preHour]
  }
  Fn.zstdRaw()
}, 3600000) // 每小时 删除上一小时的缓存

// 首次执行
setTimeout(() => {
  Fn.zstdRaw() // 压缩上上小时的文件为zstd
}, 10000)

const Adb = require('./mod.js')
global.Thm = require('./forkm.js')
const main = async () => {
  Thm.init(() => {
    Adebug.info('adb start ok')
    const proxy = require('./http')()
    require('./io')(proxy)
  })
  // require('./test')
}
main()
